﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack;
using ServiceStack.Redis;
using ServiceStack.Redis.Generic;

namespace SmartFrame_DataCollect
{
    /// <summary>
    /// Redis对象帮助类
    /// </summary>
    /// <typeparam name="TEntity">实体对象模板</typeparam>
    public class RedisHelper<TEntity> : RedisRepositoryBase<TEntity> where TEntity : Entity
    {
        public TEntity Insert(TEntity entity,DateTime? expireTime=null)
        {
            if(expireTime==null)
            {
                expireTime = DateTime.Now.AddDays(1);
            }
            return base.Insert(entity,(DateTime)expireTime);
        }

        public void Update(TEntity entity,DateTime? expireTime=null)
        {
            if(expireTime==null)
            {
                expireTime = DateTime.Now.AddDays(1);
            }
            base.Update(entity,(DateTime)expireTime);
        }

        public TEntity GetById(object Id)
        {
            return base.GetById(Id);
        }

        public IList<TEntity> GetList(Func<TEntity, bool> predicate)
        {
            return base.GetList(predicate);
        }
    }

    public class RedisHelper
    {
        public List<string> listConnAddress { get; set; }
        public RedisHelper(List<string> _listConnAddress)
        {
            listConnAddress = _listConnAddress;
        }




        public string Get(string key,long db)
        {
            using (var redisClient = RedisManager.GetClient(listConnAddress))
            {
                //redisClient.GetKeysByPattern("")
                redisClient.Db = db;

                return redisClient.Get<string>(key);
            }
        }

        public Dictionary<string,string> GetByPattern(string pattern, long db)
        {
            using (var redisClient = RedisManager.GetClient(listConnAddress))
            {
                redisClient.Db = db;
                List<string> listKeys = redisClient.GetKeysByPattern(pattern).ToList();
                Dictionary<string, string> dicValue = new Dictionary<string, string>();
                if (listKeys.Count>0)
                {
                    dicValue = redisClient.GetAll<string>(listKeys) as Dictionary<string, string>;
                }
                
                return dicValue;
            }
        }


        public void Set(string key,string value,DateTime? expireTime, long db)
        {
            using (var redisClient = RedisManager.GetClient(listConnAddress))
            {
                redisClient.Db = db;
                if (expireTime == null)
                {
                    expireTime = DateTime.Now.AddDays(1);
                }
                redisClient.Set<string>(key, value,(DateTime)expireTime);
            }
        }

    }

}
